package ygflower.controller;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.validation.BindException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import ygflower.dao.FlowerDao;

public abstract class FileUploadController extends AbstractController{
	public static  String ErrorMessages = "errorMessages";
	public static  String FileName = "FileName";
	
    public  String parameterFile = "parameterFile";
	private String formView;

	private String successView;
    public String getFormView() {
		return formView;
	}
	public void setFormView(String formView) {
		this.formView = formView;
	}
	public String getSuccessView() {
		return successView;
	}
	public void setSuccessView(String successView) {
		this.successView = successView;
	}
	public String getParameterFile() {
		return parameterFile;
	}
	public void setParameterFile(String parameterFile) {
		this.parameterFile = parameterFile;
	}
	static Logger log = Logger.getLogger(FileUploadController.class);
    
    private String folder;
    FlowerDao flowerDap;
     public void setFlowerDap(FlowerDao flowerDap) {
		this.flowerDap = flowerDap;
	}
	public String getFolder() {
		return folder;
	}
	public void setFolder(String folder) {
		this.folder = folder;
	}
//	protected ModelAndView handleRequestInternal(HttpServletRequest request,
//			HttpServletResponse response) throws Exception {
//		if(request instanceof MultipartHttpServletRequest){
//			MultipartHttpServletRequest multipart = (MultipartHttpServletRequest) request;
//			MultipartFile file = multipart.getFile(parameterFile);
//			if(file == null || file.isEmpty()){
//				// if file not exist
//				response.sendError(HttpServletResponse.SC_BAD_REQUEST);
//				return new ModelAndView(getFormView());
//			}
//			String filename = file.getOriginalFilename();
//			log.info("Upload file name: "+filename);
//			
//			String ext = "";
//			int pos;
//			if((pos = filename.lastIndexOf(".")) != -1){
//				ext = java.net.URLEncoder.encode(filename.substring(pos).trim(), "UTF-8");
//			}
//			InputStream input = null;
//			OutputStream output = null;
//			
//			String uploadFile = request.getSession().getServletContext().getRealPath(getFolder() + "/" +System.currentTimeMillis() + ext);
//			
//			
//			try {
//				input = file.getInputStream();
//				output = new BufferedOutputStream(new FileOutputStream(uploadFile));
//				byte[] buffer =new byte[1024];
//				int n;
//				while((n = input.read(buffer)) !=  -1){
//					output.write(buffer , 0, n);
//				}
//			} finally{
//				if(input != null){
//					input.close();
//				}
//				if(output != null){
//					output.close();
//				}
//			}
//			Map model = new HashMap();
//			return new ModelAndView(getSuccessView(),model);
//		}else
//		{
//			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
//			return new ModelAndView(getFormView());
//		}
//	}
	
	
	protected void parseUploadFile(HttpServletRequest request,
			HttpServletResponse response)
			throws Exception {
		
		if(request instanceof MultipartHttpServletRequest){
			MultipartHttpServletRequest multipart = (MultipartHttpServletRequest) request;
			MultipartFile file = multipart.getFile(parameterFile);
			if(file == null || file.isEmpty()){
				// if file not exist
				return ;
			}
			String filename = file.getOriginalFilename();
			log.info("Upload file name: "+filename);
			
			String ext = "";
			int pos;
			if((pos = filename.lastIndexOf(".")) != -1){
				ext = java.net.URLEncoder.encode(filename.substring(pos).trim(), "UTF-8");
			}
			InputStream input = null;
			OutputStream output = null;
			
			//the file name store 
			filename += System.currentTimeMillis() + ext;
			String uploadFile = request.getSession().getServletContext().getRealPath(getFolder() + "/" + filename );
			
			
			try {
				input = file.getInputStream();
				output = new BufferedOutputStream(new FileOutputStream(uploadFile));
				byte[] buffer =new byte[1024];
				int n;
				while((n = input.read(buffer)) !=  -1){
					output.write(buffer , 0, n);
				}
			} finally{
				if(input != null){
					input.close();
				}
				if(output != null){
					output.close();
				}
			}
			request.setAttribute(FileName, filename);
			Map model = new HashMap();
//			model.put("command", command);
			
		}else
		{
		}
	}
	protected boolean isFormSubmission(HttpServletRequest request) {
		return "POST".equals(request.getMethod());
	}	
	protected final ModelAndView showNewForm(HttpServletRequest request, HttpServletResponse response)
	throws Exception {

logger.debug("Displaying new form");
return showForm(request, getFormView(),null);
}
	protected final ModelAndView showForm(
			HttpServletRequest request, String viewName, Map controlModel)
			throws Exception {
		Map model = new HashMap();
		if(controlModel != null){
			model.putAll(controlModel);
		}
		// Trigger rendering of the specified view, using the final model.
		return new ModelAndView(viewName, model);
	}
	abstract Map<String,String> validatorUpload(HttpServletRequest request, Object command);
}
